# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
import random
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware


class SnowballSlaveSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)


class SnowballSlaveDownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        return None

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)

class HttpProxyMiddleware(object):
    '''
    添加代理
    '''
    def process_request(self, request, spider):
        # proxy = requests.get("http://tvp.daxiangdaili.com/ip/?tid=559775358931681&num=1").text
        proxy_list = [
            '218.21.230.156:808',
            '115.210.181.31:34301',
            '123.161.152.38:23201',
            '222.85.5.187:26675',
            '123.161.152.31:23127',
        ]

        # 随机选择一个代理
        proxy = random.choice(proxy_list)

        # proxies = {
        #     'http': 'http://' + proxy,
        #     'https': 'https://' + proxy,
        # }
        request.meta['proxy'] = 'https://' + proxy_list[0]

class MyUserAgentMiddleware(UserAgentMiddleware):
    '''
    设置User-Agent
    '''

    def __init__(self, user_agent):
        self.user_agent = user_agent

    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            user_agent=crawler.settings.get('USER_AGENT_LIST')
        )

    def process_request(self, request, spider):
        agent = random.choice(self.user_agent)
        print(agent)
        request.headers['User-Agent'] = agent
        request.cookies={"yfx_c_g_u_id_10000079":"ck20031314022618893683755114137",
                         "smidV2":"2020031314022780377fd1969b81488b7fdc8bd8db847f0044ca2665aecaa70",
                         "PHPSESSID":"tam5veb7im3u6kfs0oe1rgdf8v",
                         "_ga":"GA1.2.1640665300.1584095808",
                         "_gid":"GA1.2.1270323324.1584095808",
                         "yfx_c_g_u_id_10000001":"ck20031318364817171801331728611",
                         "__TD_deviceId":"7KBHJ1EBOJHDBNLL",
                         "Hm_lvt_94ed3d23572054a86ed341d64b267ec6":"1584095809",
                         "_dx_uzZo5y":"c6a26eaebbc79f28bc49765c7334b677e936a249f181179264449f076adb2f0e07787eb3",
                         "yfx_f_l_v_t_10000079":"f_t_1584079346871__r_t_1584079346871__v_t_1584098833838__r_c_0",
                         "yfx_c_g_u_id_10000124":"_ck20031319272011290713745031237",
                         "yfx_f_l_v_t_10000124":"f_t_1584098840069__r_t_1584098840069__v_t_1584098840069__r_c_0",
                         "ershoufang_BROWSES":"500123431%2C500516943",
                         "_Jo0OQK":"196B213D1D8B9B6DB345AFF2C53E977D23A2425FCAADA2EB1B2F8FC1EFEF0E1B5C6BE1CF5C81D9FEC86824B8DBDD62441DDB97145EC679F47C44DEDEE6D0C21AB4AC57212F12283777CCBD6447A6849685F840763663251ADEB9AC363E13B44271116B75375CFA1B530GJ1Z1Ig==",
                         "yfx_f_l_v_t_10000001":"f_t_1584095808704__r_t_1584196230228__v_t_1584196230228__r_c_2",
                         "Hm_lpvt_94ed3d23572054a86ed341d64b267ec6":"1584196231"}
        print('=============')
        print(request.meta)